﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SugarWebApi
{
	public class SugarWebUtil
	{

		public static string ComputePasswordDigest(
			string password,
			string encryptionkey)
		{
			return
				Hex(
					(string.IsNullOrEmpty(encryptionkey)) ?
						MD5(password) :
						TripleDES(password, encryptionkey));
		}

		private static byte[] MD5(string text)
		{
			return System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.Default.GetBytes(text));
		}

		private static byte[] TripleDES(string password, string encryptionkey)
		{
			string userpass = password;

			using (TripleDES des = new TripleDESCryptoServiceProvider())
			{
				des.Mode = CipherMode.CBC;
				des.Key = Encoding.Default.GetBytes(Hex(MD5(encryptionkey)).Substring(0, 24));
				des.IV = Encoding.Default.GetBytes("password");
				des.Padding = PaddingMode.Zeros;

				return
					des.CreateEncryptor().TransformFinalBlock(
						Encoding.Default.GetBytes(userpass),
						0,
						Encoding.Default.GetByteCount(userpass)
						);
			}
		}

		private static string Hex(byte[] bytes)
		{
			StringBuilder s = new StringBuilder();
			foreach (byte b in bytes)
			{
				s.Append(b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture));
			}
			return s.ToString();
		}
	}
}
